/**
 * @fileOverview drag node hover group and add group
 * @author huangtonger@aliyun.com
 */
const Page = require('../../base/');
const Global = require('../global');

Page.registerBehaviour('dragNodeAddToGroup', diagram => {
  const graph = diagram.getGraph();
  let node;
  let group;

  // 鼠标移入合组
  graph.behaviourOn('dragenter', ev => {
    if (!diagram.getSignal('panningItem')) {
      return;
    }
    const panItems = diagram.get('panItems');

    if (panItems[0]
      && panItems[0].isNode
      && panItems.length === 1
      && ev.item
      && ev.item.isGroup
      && (panItems[0].getParent() !== ev.item)) {
      node = panItems[0];
      group = ev.item;
      graph.update(group, {
        padding: Global.groupBackgroundPadding.map(v => {
          return v + 4;
        }),
        style: Global.dragNodeHoverToGroupStyle
      });
    }
  });

  // 鼠标移出取消，移入组的激活状态
  graph.behaviourOn('dragleave', () => {
    if (!group || !node) {
      return;
    }
    graph.update(group, {
      padding: undefined,
      style: undefined
    });
  });

  // 释放鼠标合组
  graph.behaviourOn('drop', ev => {
    if (!group || !node || group !== ev.item) {
      return;
    }
    diagram.setSignal('dragaddnodetogroup', true);
    const nodeId = node.id;
    const groupId = group.id;
    graph.update(groupId, {
      padding: undefined,
      style: undefined,
      collapsed: false
    });
    function method() {
      graph.update(nodeId, {
        parent: groupId
      });
    }
    const editor = diagram.editor;
    if (editor) {
      editor.executeCommand(method);
    } else {
      method();
    }
  });
  graph.behaviourOn('dragend', () => {
    resetStatus();
  });
  // 鼠标移出画布取消合组行为
  graph.behaviourOn('canvas:mouseleave', () => {
    if (group) {
      graph.update(group, {
        padding: undefined,
        style: undefined
      });
      resetStatus();
    }
  });
  function resetStatus() {
    diagram.setSignal('dragaddnodetogroup', false);
    node = undefined;
    group = undefined;
  }
});
